package com.agileboot.domain.performance.submission.query;

import cn.hutool.core.util.StrUtil;
import com.agileboot.common.core.page.AbstractPageQuery;
import com.agileboot.domain.performance.submission.db.SubmissionEntity;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import lombok.Data;
import lombok.EqualsAndHashCode;

/**
 * 绩效上报项查询类
 */
@EqualsAndHashCode(callSuper = true)
@Data
public class SubmissionQuery extends AbstractPageQuery<SubmissionEntity> {
    private Long id;
    private String title;
    private String status;
    private Integer assessmentYear;
    private String mainCategory;
    private String subCategory;
    private String itemCategory;
    private Integer currentAuditLevel;
    private Integer owner;

    @Override
    public QueryWrapper<SubmissionEntity> addQueryCondition() {
        QueryWrapper<SubmissionEntity> queryWrapper = new QueryWrapper<SubmissionEntity>()
                .eq(assessmentYear != null, "assessment_year", assessmentYear)
                .eq(id != null, "id", id)
                .eq(StrUtil.isNotEmpty(status), "status", status)
                .like(StrUtil.isNotEmpty(title), "title", title)
                .like(StrUtil.isNotEmpty(subCategory), "sub_category", subCategory)
                .like(StrUtil.isNotEmpty(itemCategory), "item_category", itemCategory)
                .eq(currentAuditLevel != null, "current_audit_level", currentAuditLevel)
                .eq(owner != null, "owner", owner);
        if (StrUtil.isNotEmpty(mainCategory)) {
            List<String> categories = Arrays.stream(mainCategory.split(";"))
                    .map(String::trim)
                    .filter(StrUtil::isNotEmpty)
                    .collect(Collectors.toList());
            if (!categories.isEmpty()) {
                queryWrapper.and(wrapper -> {
                    for (int i = 0; i < categories.size(); i++) {
                        wrapper.like("main_category", categories.get(i));
                        if (i < categories.size() - 1) {
                            wrapper.or();
                        }
                    }
                });
            }
        }
        
        this.setTimeRangeColumn("create_time");

        return queryWrapper;
    }

    /**
     * 重写排序方法，实现自定义排序逻辑
     * 首先按status排序（REJECTED > DRAFT > PENDING_AUDIT > APPROVED），然后按创建时间降序
     */
    @Override
    public void addSortCondition(QueryWrapper<SubmissionEntity> queryWrapper) {
        if (queryWrapper == null) {
            return;
        }
        // 自定义排序：首先按status排序，然后按创建时间降序
        queryWrapper.last("ORDER BY " +
            "CASE status " +
            "WHEN 'REJECTED' THEN 1 " +
            "WHEN 'DRAFT' THEN 2 " +
            "WHEN 'PENDING_AUDIT' THEN 3 " +
            "WHEN 'APPROVED' THEN 4 " +
            "ELSE 5 " +
            "END ASC, " +
            "create_time DESC");
    }
}
